package com.googlecode.afdbaccess.web.common.interceptors;

import java.util.Enumeration;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

@RequestLogged
@Interceptor
public class RequestExtendedLoggerInterceptor {
    private final static Logger log = Logger.getLogger(RequestExtendedLoggerInterceptor.class);

    @AroundInvoke 
    public Object logRequest(InvocationContext invocationContext) throws Exception {
        HttpServletRequest request = findRequest(invocationContext);

        if(request != null) {
            logFormParameters(request);
        }
        
        return invocationContext.proceed();
    }

    private HttpServletRequest findRequest(InvocationContext invocationContext) {
        for(Object parameter:invocationContext.getParameters()) {
            if(parameter instanceof HttpServletRequest) {
                return (HttpServletRequest)parameter;
            }
        }

        return null;
    }
    
    private void logFormParameters(HttpServletRequest request) {
        log.debug("Dumping posted parameters:");

        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String[] parameterValues = request.getParameterValues(parameterName);
            for(String value : parameterValues) {
              log.debug("Parameter " + parameterName + "=" + value);
            }
        }
    }
}